package com.wx.demo.command;

import com.wx.demo.enhancer.MyAdvice;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;
import java.util.Objects;
import java.util.Scanner;

public class ClassCommand {

    public static void enhanceClass(Instrumentation inst) {
        System.out.println("请输入类名：");
        Scanner scanner = new Scanner(System.in);
        String className = scanner.next();
        Class[] allLoadedClasses = inst.getAllLoadedClasses();
        for (Class allLoadedClass : allLoadedClasses) {
            if (Objects.equals(allLoadedClass.getName(), className)) {
                new AgentBuilder.Default()
                        //禁止byte dody 在处理时修改类名
                        .disableClassFormatChanges()
                        //处理时使用retransform增强
                        .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
                        //打印出错误日志
                        .with(new AgentBuilder.Listener.WithTransformationsOnly(AgentBuilder.Listener.StreamWriting
                                .toSystemOut()))
                        //匹配哪些类
                        .type(ElementMatchers.named(className))
                        .transform((builder, typeDescription, classLoader, javaModule, protectionDomain) ->
                                builder.visit(Advice.to(MyAdvice.class).on(ElementMatchers.any())))
                        .installOn(inst);
            }
        }
    }
}
